<template>
  <el-row class="s1" v-loading.fullscreen.lock="loading">
    <el-row class="cm">
      <el-form :inline="true">
        <el-form-item label="角色名">
          <el-input v-model="search.roleName" placeholder="角色名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="queryList">查询</el-button>
        </el-form-item>
      </el-form>
      <div style="float: right;background-color: #fafafa;margin-bottom: 15px;">
        <el-button type="success" icon="el-icon-plus" @click="handleAdd">新增</el-button>
        <el-button type="warning" icon="el-icon-edit" @click="handleEdit">编辑</el-button>
        <el-button type="info" icon="el-icon-unlock" @click="handleApiPermission">接口权限</el-button>
        <el-button type="info" icon="el-icon-unlock" @click="handleMenuPermission">页面权限</el-button>
        <el-popover placement="top" width="160" v-model="delVisible">
          <p>确定删除吗？</p>
          <div style="text-align: right; margin: 0">
            <el-button size="mini" type="text" @click="delVisible = false">取消</el-button>
            <el-button size="mini" type="danger" @click="handleDelete">确定</el-button>
          </div>
          <el-button style="margin-left: 10px" slot="reference" icon="el-icon-delete" type="danger">删除</el-button>
        </el-popover>
      </div>
      <el-table highlight-current-row :data="tableData" @selection-change="handleSelectionChange" ref="multipleTable" @row-click="handleCheckChange"
        stripe style="width: 100%">
        <el-table-column type="selection" width="50">
        </el-table-column>
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="roleName" label="角色">
        </el-table-column>
        <el-table-column prop="branchName" label="所属商户">
        </el-table-column>
        <el-table-column prop="roleName" label="状态">
          <template slot-scope="scope">
            <span>{{scope.row.status===1?'启用':'禁用'}}</span>
          </template>
        </el-table-column>
      </el-table>

      <table-pagination v-if="pagination.totalCount!==0" :pagination="pagination" @change="pageChange"></table-pagination>
    </el-row>

    <el-dialog :title="title" width="400px" :close-on-click-modal="false" :visible.sync="dialogVisible">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="角色">
          <el-input v-model="form.roleName"></el-input>
        </el-form-item>
        <el-form-item label="总店名称">
          <el-select v-model="form.branchId" placeholder="请选择总店" style="width: 100%" clearable>
            <el-option v-for="item in branchs" :key="item.branchId" :label="item.branchName" :value="item.branchId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="启用" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUser">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="接口权限" width="400px" :close-on-click-modal="false" :visible.sync="dialogVisible1">
      <el-tree :data="apiData" node-key="id" show-checkbox ref="apiTree" :default-checked-keys="apiChecked">
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="saveApiPer">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="菜单权限" width="400px" :close-on-click-modal="false" :visible.sync="dialogVisible2">
      <el-tree :data="menuData" node-key="id" show-checkbox ref="menuTree" :default-checked-keys="menuChecked">
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="saveMenuPer">确 定</el-button>
      </span>
    </el-dialog>
  </el-row>
</template>

<script>
  import PermissionApi from 'services/permissionApi';

  import TablePagination from 'commonComponents/tablePagination';

  import Pagination from 'models/pagination';
  import RoleListSearch from 'models/permission/roleListSearch';

  export default {
    data() {
      return {
        loading: false,
        title: '编辑',
        pagination: new Pagination(),
        search: new RoleListSearch(),
        tableData: [],
        delVisible: false,
        dialogVisible: false,
        dialogVisible1: false,
        dialogVisible2: false,
        form: {},
        roles: [],
        multipleSelection: [],
        apiData: [],
        apiChecked: [],
        menuData: [],
        menuChecked: [],
        branchs: []
      }
    },

    created() {
      this.loading = true;
      Promise.all([
        this.setBranchs(),
        this.setRolList(false)
      ]).then(() => {
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    methods: {
      setBranchs() {
        return PermissionApi.getBranchList().then(branchs => {
          this.branchs = branchs;
          return branchs;
        });
      },

      setRolList(hasLoading = true) {
        if (hasLoading) {
          this.loading = true;
        }
        return PermissionApi.getAllRoleList(this.search, this.pagination).then(roleList => {
          this.tableData = roleList;
          if (hasLoading) {
            this.loading = false;
          }
          return roleList;
        }).catch(() => {
          if (hasLoading) {
            this.loading = false;
          }
        });
      },

      saveUser() {
        this.loading = true;
        if (this.form.roleId) {
          //更新
          PermissionApi.updateRole(this.form).then(msg => {
            this.$message(msg);
            this.dialogVisible = false;
            this.loading = false;
            this.setRolList();
          }).catch(() => {
            this.loading = false;
          });
        } else {
          //新增
          PermissionApi.addRole(this.form).then(msg => {
            this.$message(msg);
            this.dialogVisible = false;
            this.loading = false;
            this.setRolList();
          }).catch(() => {
            this.loading = false;
          });
        }
      },

      handleApiPermission() {
        if (!this.operateTips('edit', this.multipleSelection.length)) {
          return;
        }
        let row = this.multipleSelection[0];
        this.loading = true;
        PermissionApi.getPermissionApiList(row.roleId).then(res => {
          this.apiData = res.apiData;
          this.apiChecked = res.apiChecked;
          this.loading = false;
          this.dialogVisible1 = true;
        }).catch(() => {
          this.loading = false;
        });
      },

      saveApiPer() {
        if (!this.operateTips('edit', this.multipleSelection.length)) {
          return;
        }
        let row = this.multipleSelection[0];
        this.loading = true;
        PermissionApi.savePermissionApiData({
          roleId: row.roleId,
          pids: this.$refs.apiTree.getCheckedKeys()
        }).then(msg => {
          this.$message(msg);
          this.dialogVisible1 = false;
          this.loading = false;
        }).catch(() => {
          this.loading = false;
        });
      },

      handleMenuPermission() {
        if (!this.operateTips('edit', this.multipleSelection.length)) {
          return;
        }
        let row = this.multipleSelection[0];
        this.loading = true;
        PermissionApi.getMenuList(row.roleId).then(res => {
          this.menuData = res.menuData;
          this.menuChecked = res.menuChecked;
          this.loading = false;
          this.dialogVisible2 = true;
        }).catch(() => {
          this.loading = false;
        });
      },

      saveMenuPer() {
        let nodes = this.$refs.menuTree.getCheckedNodes(false, true);
        let pids = _.map(nodes, 'id');

        if (!this.operateTips('edit', this.multipleSelection.length)) {
          return;
        }
        let row = this.multipleSelection[0];
        this.loading = true;
        PermissionApi.saveMenuData({
          roleId: row.roleId,
          pids: pids
        }).then(msg => {
          this.$message(msg);
          this.dialogVisible2 = false;
          this.loading = false;
        }).catch(() => {
          this.loading = false;
        });
      },

      pageChange() {
        this.setRolList();
      },

      handleSelectionChange(val) {
        this.multipleSelection = val;
      },

      handleCheckChange(row, event, column) {
        if (row) {
          this.$refs.multipleTable.toggleRowSelection(row);
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },

      operateTips(type, sl) {
        if (sl === 0) {
          this.$message({
            message: '请选择一个条目',
            type: 'warning'
          });
        } else if (sl === 1) {
          return true;
        } else {
          if (type === 'edit') {
            this.$message({
              message: '只能选择一个条目',
              type: 'warning'
            });
          } else if (type === 'del') {
            return true;
          }
        }
        return false;
      },

      handleEdit() {
        this.title = '编辑';
        if (!this.operateTips('edit', this.multipleSelection.length)) {
          return;
        }
        let row = this.multipleSelection[0];
        this.form = Object.assign({}, row);
        this.dialogVisible = true;
      },

      handleDelete(index, row) {
        if (!this.operateTips('del', this.multipleSelection.length)) {
          return;
        }
        let rows = this.multipleSelection;
        let ids = _.map(rows, 'roleId');
        this.loading = true;
        PermissionApi.delRole(ids).then(msg => {
          this.$message(msg);
          this.setRolList();
          this.loading = false;
          this.delVisible = false;
        }).catch(() => {
          this.loading = false;
        });
      },

      handleAdd() {
        this.title = '新增';
        this.form = {
          roleName: '',
          branchId: '',
          status: 1
        };
        this.dialogVisible = true;
      },

      queryList() {
        this.pagination.currentPage = 1;
        this.setRolList();
      }
    },

    components: {
      TablePagination
    }
  }

</script>

<style scoped>
  .cm {
    width: 98%;
    margin-top: 15px;
    margin-left: 1%;
  }

  .s1 {
    width: 100%;
    height: 100%;
    background-color: #f1f3f4
  }

</style>
